package com.aiyige.page.portal;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;

import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.city.util.CityUtil;
import com.aiyige.im.SessionHelper;
import com.aiyige.im.mixpush.DemoMixPushMessageHandler;
import com.aiyige.page.login.model.impl.LoginManager;
import com.aiyige.utils.AppErrorDialog;
import com.aiyige.utils.AppUtils;
import com.aiyige.utils.PermissionUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.widget.RequestPermissionDialog;
import com.alibaba.fastjson.JSON;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.NimIntent;
import com.netease.nimlib.sdk.mixpush.MixPushService;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class PortalPage extends AppCompatActivity implements DialogInterface.OnCancelListener {
    public static final int REQUEST_CODE_GO_TO_APP_SETTING = 123;
    InitTask initTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PortalPagePermissionsDispatcher.checkPermissionWithPermissionCheck(this);
    }

    @Override
    public void onBackPressed() {
    }


    public void initApp() {
        initTask = new InitTask();
        initTask.execute();
    }

    @NeedsPermission({
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.READ_PHONE_STATE
    })
    void checkPermission() {
        initApp();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PortalPagePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.READ_PHONE_STATE
    })
    void onShowRationale(final PermissionRequest request) {
        List<String> ungrantedPermissionList = PermissionUtil.pickUngrantedPremission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                Manifest.permission.READ_PHONE_STATE
        );
        List<String> ungrantedPermissionTitleList = PermissionUtil.batchConvertPermissionToReadableString(this, ungrantedPermissionList);
        RequestPermissionDialog requestPermissionDialog = RequestPermissionDialog.newInstance(StringUtils.getString(R.string.app_need_permission), TextUtils.join("\n", ungrantedPermissionTitleList));
        requestPermissionDialog.setListner(new RequestPermissionDialog.Listener() {
            @Override
            public void onClickOk() {
                request.proceed();
            }

            @Override
            public void onCancel() {
                finish();
            }
        });
        requestPermissionDialog.show(getSupportFragmentManager(), "");

    }

    @OnPermissionDenied({
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.READ_PHONE_STATE
    })
    void onPermissionDenied() {
        List<String> ungrantedPermissionList = PermissionUtil.pickUngrantedPremission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                Manifest.permission.READ_PHONE_STATE

        );
        List<String> ungrantedPermissionTitleList = PermissionUtil.batchConvertPermissionToReadableString(this, ungrantedPermissionList);
        RequestPermissionDialog requestPermissionDialog = RequestPermissionDialog.newInstance(StringUtils.getString(R.string.app_really_need_permission), StringUtils.getString(R.string.please_grant_permission), StringUtils.getString(R.string.ok2));
        requestPermissionDialog.setListner(new RequestPermissionDialog.Listener() {
            @Override
            public void onClickOk() {
                PortalPagePermissionsDispatcher.checkPermissionWithPermissionCheck(PortalPage.this);
            }

            @Override
            public void onCancel() {
                finish();
            }
        });
        requestPermissionDialog.show(getSupportFragmentManager(), "");
    }

    @OnNeverAskAgain({
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.READ_PHONE_STATE
    })
    void onNeverAskAgain() {
        List<String> ungrantedPermissionList = PermissionUtil.pickUngrantedPremission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                Manifest.permission.READ_PHONE_STATE
        );
        List<String> ungrantedPermissionTitleList = PermissionUtil.batchConvertPermissionToReadableString(this, ungrantedPermissionList);
        RequestPermissionDialog requestPermissionDialog = RequestPermissionDialog.newInstance(StringUtils.getString(R.string.grant_permission_in_setting), TextUtils.join("\n", ungrantedPermissionTitleList));
        requestPermissionDialog.setListner(new RequestPermissionDialog.Listener() {
            @Override
            public void onClickOk() {
                AppUtils.gotoAppSetting(PortalPage.this, REQUEST_CODE_GO_TO_APP_SETTING);
            }

            @Override
            public void onCancel() {
                finish();
            }
        });
        requestPermissionDialog.show(getSupportFragmentManager(), "");

    }

    @Override
    public void onCancel(DialogInterface dialog) {
        finish();
    }

    public class InitTask extends AsyncTask<Object, Object, Object> {
        @Override
        protected void onPreExecute() {
            CityUtil.installUpdateAlarm();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                CityUtil.copyCityFromAsset();
                CityUtil.populateCityList(false);
                LoginManager.getInstance().onStartAppDoSomething();
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            CityUtil.updateCityIfTooOld();
            if (o instanceof Exception) {
                AppErrorDialog.newInstance(StringUtils.getString(R.string.app_init_failed), new AppErrorDialog.Callback() {
                    @Override
                    public void onConfirm() {
                        finish();
                        System.exit(0);
                    }
                }).show(getSupportFragmentManager(), "");
            } else {
                handleIntent();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_GO_TO_APP_SETTING:
                PortalPagePermissionsDispatcher.checkPermissionWithPermissionCheck(this);
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }


    public void handleIntent() {
        Uri uri = getIntent().getData();
        if (uri != null) {
            Router.start(uri.toString());
            finish();
        } else {
            onIntent();
            finish();
        }
    }


    // 处理收到的Intent
    private void onIntent() {
        // 已经登录过了，处理过来的请求
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT)) {
            ArrayList<IMMessage> messages = (ArrayList<IMMessage>) intent.getSerializableExtra(NimIntent.EXTRA_NOTIFY_CONTENT);
            parseNotifyIntent(new Intent().putExtra(NimIntent.EXTRA_NOTIFY_CONTENT, messages.get(0)));
        } else if (NIMClient.getService(MixPushService.class).isFCMIntent(intent)) {
            parseFCMNotifyIntent(NIMClient.getService(MixPushService.class).parseFCMPayload(intent));
        }

    }

    private void parseNotifyIntent(Intent intent) {
        if (intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT)) {
            IMMessage message = (IMMessage) intent.getSerializableExtra(NimIntent.EXTRA_NOTIFY_CONTENT);
            switch (message.getSessionType()) {
                case P2P:
                    SessionHelper.startP2PSession(this, message.getSessionId());
                    break;
                default:
                    break;
            }
        }
    }


    private void parseFCMNotifyIntent(String payloadString) {
        Map<String, String> payload = JSON.parseObject(payloadString, Map.class);
        String sessionId = payload.get(DemoMixPushMessageHandler.PAYLOAD_SESSION_ID);
        String type = payload.get(DemoMixPushMessageHandler.PAYLOAD_SESSION_TYPE);
        if (sessionId != null && type != null) {
            int typeValue = Integer.valueOf(type);
            IMMessage message = MessageBuilder.createEmptyMessage(sessionId, SessionTypeEnum.typeOfValue(typeValue), 0);
            onParseIntent(new Intent().putExtra(NimIntent.EXTRA_NOTIFY_CONTENT, message));
        }
    }

    private void onParseIntent(Intent intent) {
        if (intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT)) {
            IMMessage message = (IMMessage) getIntent().getSerializableExtra(NimIntent.EXTRA_NOTIFY_CONTENT);
            switch (message.getSessionType()) {
                case P2P:
                    SessionHelper.startP2PSession(this, message.getSessionId());
                    break;
//                case Team:
//                    SessionHelper.startTeamSession(this, message.getSessionId());
//                    break;
                default:
                    break;
            }
        }
    }
}
